package com.allwees.bs.c.module.user.listener;

import com.allwees.bs.c.module.user.entity.UserEntity;
import com.allwees.bs.c.module.user.event.UserUpdatedEvent;
import com.allwees.bs.c.module.user.repository.UserRepository;
import com.allwees.core.common.util.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionalEventListener;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.AwsCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.ObjectCannedACL;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;

import java.io.IOException;
import java.net.URL;
import java.util.Date;

@Slf4j
@Component
public class UserUpdatedListener {

    @Autowired
    protected UserRepository userDao;

    @TransactionalEventListener
    public void onEvent(UserUpdatedEvent event) {
        try {
            UserEntity user = (UserEntity) event.getSource();
            String avatar = user.getAvatar();
            if (StringUtils.isNotBlank(avatar) && !StringUtils.contains(avatar,"allwees.com")) {
                log.info("===> avatar before:{}",avatar);
                avatar = uploadToAws(user.getUuid(),avatar);
                log.info("===> avatar after:{}",avatar);
                if (StringUtils.isNotBlank(avatar)) {
                    user.setAvatar(avatar);
                    userDao.save(user);
                }
            }
        } catch (Exception e) {
            log.error("===>upload avrtar to aws error.",e);
        }
    }

    private static final String URL_PATTERN = "https://%s/%s";

    private String uploadToAws(String userUuid, String photo) throws IOException {
        URL url = new URL(photo);
        byte[] bytes = IOUtils.toByteArray(url);
        String path = url.getPath();
        String suffix = path.substring(path.lastIndexOf('/'));
        String date = DateUtil.formatDate(new Date(), "yyyyMMdd");
        String objectKey = "avr/" + userUuid + "/" + date + suffix;
        PutObjectRequest putObjectRequest = PutObjectRequest.builder()
                .bucket("cdn-allwees")
                .contentType("image/png")
                .key(objectKey)
                .acl(ObjectCannedACL.PUBLIC_READ)
                .build();
        getClient().putObject(putObjectRequest, RequestBody.fromBytes(bytes));
        return String.format(URL_PATTERN, "cdn.allwees.com", objectKey);
    }

    private S3Client getClient() {
        AwsCredentials credentials = AwsBasicCredentials.create("AKIAIN3B42OZREJBKBGA", "bRFWRpS/4JIjNiJSJlUcKr8NUEbDhlGBkTixtFaG");
        return S3Client.builder()
                .credentialsProvider(StaticCredentialsProvider.create(credentials))
                .region(Region.US_WEST_1)
                .build();
    }
}
